package com.danciyixue.boot.dcyx.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.danciyixue.boot.dcyx.mapper.DailyTimeRecordsMapper;
import com.danciyixue.boot.dcyx.service.DailyTimeRecordsService;
import com.danciyixue.boot.dcyx.model.entity.DailyTimeRecords;
import com.danciyixue.boot.dcyx.model.form.DailyTimeRecordsForm;
import com.danciyixue.boot.dcyx.model.query.DailyTimeRecordsQuery;
import com.danciyixue.boot.dcyx.model.vo.DailyTimeRecordsVO;
import com.danciyixue.boot.dcyx.converter.DailyTimeRecordsConverter;
import com.danciyixue.boot.core.security.util.SecurityUtils;
import java.time.LocalDate;
import java.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

/**
 * 用户每日时间记录服务实现类
 *
 * @author youlaitech
 * @since 2025-06-28 10:26
 */
@Service
@DS("dcyx")
@RequiredArgsConstructor
public class DailyTimeRecordsServiceImpl extends ServiceImpl<DailyTimeRecordsMapper, DailyTimeRecords> implements DailyTimeRecordsService {

    private final DailyTimeRecordsConverter dailyTimeRecordsConverter;
    private final DailyTimeRecordsMapper dailyTimeRecordsMapper;

    /**
    * 获取用户每日时间记录分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<DailyTimeRecordsVO>} 用户每日时间记录分页列表
    */
    @Override
    public IPage<DailyTimeRecordsVO> getDailyTimeRecordsPage(DailyTimeRecordsQuery queryParams) {
        Page<DailyTimeRecordsVO> pageVO = this.baseMapper.getDailyTimeRecordsPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }
    
    /**
     * 获取用户每日时间记录表单数据
     *
     * @param id 用户每日时间记录ID
     * @return 用户每日时间记录表单数据
     */
    @Override
    public DailyTimeRecordsForm getDailyTimeRecordsFormData(Long id) {
        DailyTimeRecords entity = this.getById(id);
        return dailyTimeRecordsConverter.toForm(entity);
    }
    
    /**
     * 新增用户每日时间记录
     *
     * @param formData 用户每日时间记录表单对象
     * @return 是否新增成功
     */
    @Override
    public boolean saveDailyTimeRecords(DailyTimeRecordsForm formData) {
        DailyTimeRecords entity = dailyTimeRecordsConverter.toEntity(formData);
        return this.save(entity);
    }
    
    /**
     * 更新用户每日时间记录
     *
     * @param id   用户每日时间记录ID
     * @param formData 用户每日时间记录表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateDailyTimeRecords(Long id,DailyTimeRecordsForm formData) {
        DailyTimeRecords entity = dailyTimeRecordsConverter.toEntity(formData);
        return this.updateById(entity);
    }
    
    /**
     * 删除用户每日时间记录
     *
     * @param ids 用户每日时间记录ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteDailyTimeRecordss(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的用户每日时间记录数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

    /**
     * 获取或创建今日在线时长记录
     *
     * @return 今日在线时长记录
     */
    @Override
    public DailyTimeRecordsVO getOrCreateTodayOnlineSeconds() {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();
        // 获取当天0点
        LocalDateTime today = LocalDate.now().atStartOfDay();

        // 查询当天记录
        DailyTimeRecords record = getTodayRecord(userId, today);

        // 如果记录不存在，则创建新记录
        if (record == null) {
            record = createNewRecord(userId, today);
        }

        // 转换为VO对象并返回
        return dailyTimeRecordsConverter.toVO(record);
    }

    /**
     * 增加今日在线时长
     *
     * @param formData 在线时长表单数据
     * @return 是否更新成功
     */
    @Override
    public boolean addTodayOnlineSeconds(DailyTimeRecordsForm formData) {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();
        // 获取当天0点
        LocalDateTime today = LocalDate.now().atStartOfDay();

        // 查询当天记录
        DailyTimeRecords record = getTodayRecord(userId, today);

        // 如果记录不存在，则创建新记录
        if (record == null) {
            record = createNewRecord(userId, today);
        }

        // 更新在线时长
        return updateTimeRecord(record, formData);
    }

    /**
     * 获取用户当日时间记录
     *
     * @param userId 用户ID
     * @param today 今天的开始时间
     * @return 用户当日时间记录
     */
    private DailyTimeRecords getTodayRecord(Long userId, LocalDateTime today) {
        return dailyTimeRecordsMapper.getTodayRecord(userId, today);
    }

    /**
     * 创建新的时间记录
     *
     * @param userId 用户ID
     * @param today 今天的开始时间
     * @return 新创建的时间记录
     */
    private DailyTimeRecords createNewRecord(Long userId, LocalDateTime today) {
        DailyTimeRecords record = new DailyTimeRecords();
        record.setUserId(userId);
        record.setRecordDate(today);
        record.setOnlineSeconds(0);
        record.setEffectiveSeconds(0);
        record.setEfficiency("0%");
        record.setOnlineTime(today);
        record.setEffectiveTime(today);

        // 保存新记录
        this.save(record);
        return record;
    }

    /**
     * 更新时间记录
     *
     * @param record 当前记录
     * @param formData 表单数据
     * @return 是否更新成功
     */
    private boolean updateTimeRecord(DailyTimeRecords record, DailyTimeRecordsForm formData) {
        boolean updated = false;

        // 更新在线时长
        if (formData.getOnlineSeconds() != null && formData.getOnlineSeconds() > 0) {
            // 累加在线秒数
            int newOnlineSeconds = record.getOnlineSeconds() + formData.getOnlineSeconds();
            record.setOnlineSeconds(newOnlineSeconds);

            // 更新在线时间
            LocalDateTime onlineTime = record.getRecordDate().plusSeconds(newOnlineSeconds);
            record.setOnlineTime(onlineTime);

            updated = true;
        }

        // 更新有效时长
        if (formData.getEffectiveSeconds() != null && formData.getEffectiveSeconds() > 0) {
            // 累加有效秒数
            int newEffectiveSeconds = record.getEffectiveSeconds() + formData.getEffectiveSeconds();
            record.setEffectiveSeconds(newEffectiveSeconds);

            // 更新有效时间
            LocalDateTime effectiveTime = record.getRecordDate().plusSeconds(newEffectiveSeconds);
            record.setEffectiveTime(effectiveTime);

            updated = true;
        }

        // 计算效率
        if (updated && record.getOnlineSeconds() > 0) {
            // 计算百分比
            double efficiencyValue = (double) record.getEffectiveSeconds() / record.getOnlineSeconds() * 100;
            // 格式化为百分比字符串，保留两位小数
            String efficiency = String.format("%.2f%%", efficiencyValue);
            record.setEfficiency(efficiency);
        }

        // 更新记录
        return this.updateById(record);
    }
}
